package com.cuitrip.business.tripservice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.cuitrip.business.tripservice.model.PictureDescription;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.utils.ImageHelper;
import com.lab.utils.KeyboardUtil;
import com.lab.widget.CTViewPager;
import com.lab.widget.WordCountView;
import com.lab.widget.photoview.PhotoView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * 图片详情列表
 * Created by ak on 4/19/16.
 */
public class PictureListActivity extends CustomUiFragmentActivity {


    public static final String KEY_PICTURE_LIST = "KEY_PICTURE_LIST";
    public static final String KEY_POSITION = "key_position";
    public static final String KEY_CAN_EDIT = "key_can_edit";

    private static final String CAN_SCROLL = "can_scroll";

    @Bind(R.id.ct_view_pager)
    CTViewPager mCtViewPager;
    ArrayList<PictureDescription> mPictureDescriptionList = new ArrayList<PictureDescription>();
    private boolean isOnEdit = false;
    private int position;
    private boolean canEdit = false;
    private PictureAdapter mPictureAdapter;


    public static void launchPictureView(Activity context, ArrayList<PictureDescription> pictureDescriptionList, int position, boolean canEdit, int code) {
        Intent intent = new Intent(context, PictureListActivity.class);
        intent.putParcelableArrayListExtra(KEY_PICTURE_LIST, pictureDescriptionList);
        intent.putExtra(KEY_POSITION, position);
        intent.putExtra(KEY_CAN_EDIT, canEdit);
        Jumper.launchActivityForResult(context, intent, code);
    }

    public static void launchPictureView(Fragment fragment, ArrayList<PictureDescription> pictureDescriptionList, int position, boolean canEdit, int code) {
        Intent intent = new Intent(fragment.getContext(), PictureListActivity.class);
        intent.putParcelableArrayListExtra(KEY_PICTURE_LIST, pictureDescriptionList);
        intent.putExtra(KEY_POSITION, position);
        intent.putExtra(KEY_CAN_EDIT, canEdit);
        fragment.startActivityForResult(intent, code);
    }


    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent.hasExtra(KEY_PICTURE_LIST)) {
            List<PictureDescription> pictureDescriptionList = getIntent().getParcelableArrayListExtra(KEY_PICTURE_LIST);
            mPictureDescriptionList.addAll(pictureDescriptionList);
        }
        if (intent.hasExtra(KEY_POSITION)) {
            position = intent.getIntExtra(KEY_POSITION, 0);
        }
        if (intent.hasExtra(KEY_CAN_EDIT)) {
            canEdit = intent.getBooleanExtra(KEY_CAN_EDIT, false);
        }
        super.onCreate(savedInstanceState, R.layout.ct_layout_view_pager);
        if (savedInstanceState != null) {
            boolean canScroll = savedInstanceState.getBoolean(CAN_SCROLL, true);
            mCtViewPager.setCanScroll(canScroll);
        }
        mCtViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                updateCurrentTitle(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void updateCurrentTitle(int position) {
        mTopbarMiddleArea.setText((position + 1) + "/" + mPictureDescriptionList.size());
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        mPictureAdapter = new PictureAdapter(mPictureDescriptionList, this);
        mCtViewPager.setAdapter(mPictureAdapter);
        mCtViewPager.setCurrentItem(position);
        mCtViewPager.setOffscreenPageLimit(0);
        updateCurrentTitle(position);
        initTopbar();
    }

    private void initTopbar() {
        mTopbar.setBackgroundColor(ResourceUtil.getColor(R.color.ct_alpha_black));
        mTopbarBottomLine.setVisibility(View.GONE);
        mTopbarLeftArea.setTextColor(ResourceUtil.getColor(R.color.ct_white));
        mTopbarRightArea.setTextColor(ResourceUtil.getColor(R.color.ct_white));
        mTopbarMiddleArea.setTextColor(ResourceUtil.getColor(R.color.ct_white));
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        saveAction();
        finish();
    }

    @Override
    public void onTopbarRightPress() {
        ChoiceDialog choiceDialog = ChoiceDialog.getInstance();
        choiceDialog.setDialogTitleVisibility(false);
        choiceDialog.setDialogMessage(getResources().getString(R.string.trip_photo_operate_delet_confirm));
        choiceDialog.setDialogCoupleStyleSetting(
                getResources().getString(R.string.operation_yes),
                getResources().getString(R.string.operation_cancel), new ChoiceDialog.DialogStyleCoupleCallback() {
                    @Override
                    public boolean onPositiveButtonClick() {
                        int i = mCtViewPager.getCurrentItem();
                        mPictureAdapter.removePage(i);
                        return false;
                    }

                    @Override
                    public boolean onNegativeButtonClick() {
                        return false;
                    }
                });
        showDialogFragment(choiceDialog);
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        config.mLeftStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        config.mTopbarCoverStyle = true;
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        if (canEdit) {
            config.mTopbarRightAreaName = getString(R.string.trash_icon);
        }
        return config;
    }

    private void saveAction() {
        Intent intent = new Intent();
        intent.putExtra(KEY_PICTURE_LIST, mPictureDescriptionList);
        setResult(RESULT_OK, intent);
    }

    private boolean isViewPagerActive() {
        return (mCtViewPager != null);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        if (isViewPagerActive()) {
            outState.putBoolean(CAN_SCROLL, mCtViewPager.isCanScroll());
        }
        super.onSaveInstanceState(outState);
    }

    public void setOnEdit(boolean onEdit) {
        isOnEdit = onEdit;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (isOnEdit) {
                int position = mCtViewPager.getCurrentItem();
                mPictureAdapter.hideKeyboard(position);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    static class PictureAdapter extends PagerAdapter {

        private WeakReference<PictureListActivity> activityWeakReference;

        private List<PictureDescription> pictureDescriptions;
        private SparseArrayCompat<View> mViewArrays = new SparseArrayCompat<>();

        public PictureAdapter(List<PictureDescription> pictureDescriptionList, PictureListActivity pictureListActivity) {
            this.pictureDescriptions = pictureDescriptionList;
            this.activityWeakReference = new WeakReference<PictureListActivity>(pictureListActivity);
        }

        public void removePage(int position) {
            this.pictureDescriptions.remove(position);
            notifyDataSetChanged();
            if (isContextValid()) {
                PictureListActivity pictureListActivity = activityWeakReference.get();
                pictureListActivity.updateCurrentTitle(pictureListActivity.mCtViewPager.getCurrentItem());
            }
        }

        @Override
        public int getCount() {
            if (isContextValid()) {
                return activityWeakReference.get().mPictureDescriptionList.size();
            } else {
                return 0;
            }
        }

        private boolean isContextValid() {
            return !(activityWeakReference == null || activityWeakReference.get() == null);
        }

        private void bindDescriptionView(PictureDescription pictureDescription, View view) {
            View editAction = ButterKnife.findById(view, R.id.edit_action);
            View editHint = ButterKnife.findById(view, R.id.description_hint);
            final TextView descriptionView = ButterKnife.findById(view, R.id.tv_description);
            descriptionView.setText(pictureDescription.getDescription());
            PictureListActivity activity = activityWeakReference.get();
            if (activity.canEdit && TextUtils.isEmpty(pictureDescription.getDescription())) {
                editHint.setVisibility(View.VISIBLE);
                editAction.setVisibility(View.VISIBLE);
            } else {
                editAction.setVisibility(View.GONE);
                editHint.setVisibility(View.GONE);
            }

        }

        private void setDescriptionViewListener(final PictureDescription pictureDescription, final View view, final int position) {

            final View mEditBlock = ButterKnife.findById(view, R.id.edit_block);
            final WordCountView imageDescription = ButterKnife.findById(view, R.id.image_description);
            imageDescription.setText(pictureDescription.getDescription());
            View hideKeyboard = ButterKnife.findById(view, R.id.hide_keyboard);
            View editLayout = ButterKnife.findById(view, R.id.edit_layout);
            final EditText editText = imageDescription.getEditView();
            final PictureListActivity activity = activityWeakReference.get();

            if (activity.canEdit) {
                editLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isContextValid()) {
                            activityWeakReference.get().setOnEdit(true);
                        }
                        mEditBlock.setVisibility(View.VISIBLE);
                        KeyboardUtil.showKeybBoard(activity, editText);
                    }
                });

                hideKeyboard.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        hideKeyboard(position);
                    }
                });
            }

        }

        public void hideKeyboard(int position) {

            if (mViewArrays.indexOfKey(position) < 0) {
                return;
            }
            View view = mViewArrays.get(position);
            PictureDescription pictureDescription = pictureDescriptions.get(position);
            final View mEditBlock = ButterKnife.findById(view, R.id.edit_block);
            final WordCountView imageDescription = ButterKnife.findById(view, R.id.image_description);
            final EditText editText = imageDescription.getEditView();
            if (isContextValid()) {
                activityWeakReference.get().setOnEdit(false);
            }
            pictureDescription.setDescription(imageDescription.getContent());
            KeyboardUtil.hideKeybBoard(activityWeakReference.get(), editText);
            mEditBlock.setVisibility(View.GONE);
            bindDescriptionView(pictureDescription, view);
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            if (isContextValid()) {
                PictureDescription pictureDescription = pictureDescriptions.get(position);
                PictureListActivity activity = activityWeakReference.get();
                View view = LayoutInflater.from(activity).inflate(R.layout.ct_layout_image, container, false);
                PhotoView photoView = ButterKnife.findById(view, R.id.picture);
                ImageHelper.displayCtImage(pictureDescription.getUrl(), photoView, null);
                bindDescriptionView(pictureDescription, view);
                setDescriptionViewListener(pictureDescription, view, position);
                //edit interaction
                container.addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                mViewArrays.append(position, view);
                return view;
            }
            return null;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            if (pictureDescriptions.contains((View) object)) {
                return pictureDescriptions.indexOf((View) object);
            } else {
                return POSITION_NONE;
            }
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

    }
}
